-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathKosaraju's Algorithm.cpp
More file actions
89 lines (73 loc) · 1.21 KB
/
Kosaraju's Algorithm.cpp
File metadata and controls
89 lines (73 loc) · 1.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
/*input
5 5
2 1
1 3
3 2
1 4
4 5
*/
/* Algorithm to Find all strongly connected components of a directed graph
Time Complexity: O(V+E)
*/
#include <iostream>
#include <vector>
#include <stack>
const int N = 100001;
std::vector < int > v[N];
std::vector < int > v1[N];
int vis1[N];
std::stack < int > s;
void dfs(int s1) {
vis1[s1] = 1;
for(auto x: v[s1]) {
if(!vis1[x]) {
dfs(x);
}
}
s.push(s1);
}
void dfs1(int s) {
vis1[s] = 2;
std::cout << s << " ";
for(auto x: v1[s]) {
if(vis1[x] <= 1) {
dfs1(x);
}
}
}
void kosaraju(int n)
{
for(int i = 1; i <= n; i ++) {
if(!vis1[i]) {
dfs(i);
}
}
while(!s.empty()) {
int p = s.top();
s.pop();
if(vis1[p] <= 1) {
dfs1(p);
std::cout << "\n";
}
}
}
int main ()
{
int n, m;
std::cin >> n >> m;
for(int i = 0; i < m; i ++) {
int x, y;
std::cin >> x >> y;
v[x].push_back(y);
v1[y].push_back(x);
}
std::cout << "Components are \n";
kosaraju(n);
return 0;
}
/* Expected Output
Components are
1 2 3
4
5
*/